package com.itjiange.service.impl;

import cn.hutool.core.util.StrUtil;
import com.itjiange.dao.UserDao;
import com.itjiange.dao.impl.UserDaoImpl;
import com.itjiange.pojo.User;
import com.itjiange.pojo.dto.user.UserRegisterDto;
import com.itjiange.service.UserService;
import com.itjiange.utils.MD5Utils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import static com.itjiange.constant.CustomConstant.logger;

/**
 * @author 大师的本
 * @description 针对表【kfm_user】的数据库操作Service实现
 * @createDate 2023-10-21 09:16:10
 */
public class UserServiceImpl implements UserService {

    private final UserDao userDao = new UserDaoImpl();

    /**
     * 用户登录
     *
     * @param username 用户名
     * @param password 用户密码
     * @param req
     * @return
     */
    @Override
    public boolean userLogin(String username, String password, HttpServletRequest req) {
        // 校验
        if (StrUtil.hasEmpty(username, password)) {
            logger.info("登录字段为空！");
            return false;
        }
        // 密码加密
        String userPassword = MD5Utils.encrypt(password);
        // 查询数据库
        User user = userDao.getByNameAndPassword(username, userPassword);
        if (user == null) {
            logger.info("用户未注册！登录失败！");
            return false;
        }
        // 设置 session
        HttpSession session = req.getSession();
        session.setAttribute("user", user);
        session.setMaxInactiveInterval(60*60);
        return true;
    }

    /**
     * 用户注册
     *
     * @param userRegisterDto 注册 User 类
     * @return
     */
    @Override
    public boolean userRegister(UserRegisterDto userRegisterDto) {
        // 解析 UserRegisterDto
        String username = userRegisterDto.getUsername();
        String password = userRegisterDto.getPassword();
        String confirmPassword = userRegisterDto.getConfirmPassword();
        String email = userRegisterDto.getEmail();
        // 校验
        if (StrUtil.hasEmpty(username, password, confirmPassword, email)) {
            logger.info("注册字段为空！注册失败！");
            return false;
        }
        if (!confirmPassword.equals(password)) {
            logger.info("密码不一致！注册失败！");
            return false;
        }
        User user = userDao.selectByUserName(username);
        if (user != null) {
            logger.info("用户已注册！注册失败！");
            return false;
        }
        // 密码加密
        String userPassword = MD5Utils.encrypt(password);
        // 存储数据至数据库
        int flag = userDao.insertUser(username, userPassword, email);
        if (flag == -1) {
            logger.info("注册失败！");
            return false;
        }
        logger.info("注册成功！");
        return true;
    }
}




